﻿using System;
using System.Configuration;
using System.Web;
using Shuba.Model;
using System.Collections.Generic;
using System.Web.UI.WebControls;

namespace Shuba.Web.master
{
    public partial class cluster_plan_add : basePage
    {
        string msg = "";
        Int64 TotalNoaCluster = 0, TotalAmountCluster = 0, TotalNoaClusterReal = 0, TotalAmountClusterReal = 0;

        private void BindData()
        {
            Shuba.Business.ClusterTarget _ClusterTarget = new Shuba.Business.ClusterTarget();
            List<ClusterTargetInfo> list;

            string TargetYear = ddlYear.Text;
            string RegionalID = ddlRegion.SelectedValue.ToString();

            list = _ClusterTarget.GetList(RegionalID, TargetYear, Session["UnitID"].ToString());
            
            gvList.DataSource = list;
            gvList.DataBind();

            Shuba.Business.RegionalTarget _RegionTarget = new Shuba.Business.RegionalTarget();
            Shuba.Model.RegionalTargetInfo bi;

            bi = _RegionTarget.Get(RegionalID, TargetYear);
            lblYear.Text = ddlYear.Text;
            lblRegion.Text = ddlRegion.SelectedItem.Text;

            lblAmount.Text = bi.TargetAmount.ToString("N0");
            lblNoa.Text = bi.Noa.ToString("N0");
            lblAmountCluster.Text = TotalAmountCluster.ToString("N0");
            lblNoaCluster.Text = TotalNoaCluster.ToString("N0");


            lblAmountReal.Text = bi.TargetAmountReal.ToString("N0");
            lblNoaReal.Text = bi.NoaReal.ToString("N0");
            lblAmountClusterReal.Text = TotalAmountClusterReal.ToString("N0");
            lblNoaClusterReal.Text = TotalNoaClusterReal.ToString("N0");

            if (gvList.Rows.Count > 0)
            {
                btnSubmit.Enabled = true;
                btnCancel.Enabled = true;
            }
            else
            {
                btnSubmit.Enabled = false;
                btnCancel.Enabled = false;
            }
        }

        protected void ddlYear_Change(object sender, EventArgs e)
        {
            BindData();
        }

        protected void ddlRegion_Change(object sender, EventArgs e)
        {
            BindData();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //this.Form.DefaultButton = btnSubmit.UniqueID;

            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("TARGET_CLUSTER");

                string SelectedYear = Request.QueryString["yr"].ToString().Trim();
                string SelectedRegion = Request.QueryString["reg"].ToString().Trim();

                if (!IsUserAdd(acl) && !IsUserEdit(acl))
                {
                    msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                LabelTitle.Text = GetPageTitle("TARGET_CLUSTER");

                InitYearList();
                InitRegionList();

                ddlYear.SelectedIndex = ddlYear.Items.IndexOf(ddlYear.Items.FindByValue(SelectedYear)); //ddlYear.Items.IndexOf(ddlYear.Items.FindByValue(ProcessingDate().Year.ToString()));
                ddlRegion.SelectedIndex = ddlRegion.Items.IndexOf(ddlRegion.Items.FindByValue(SelectedRegion));

                BindData();
                
            }
        }

        protected void InitYearList()
        {
            Int32 NextYear = Convert.ToInt32(ProcessingDate().Year.ToString()) + 4;
            Int32 LastYear = Convert.ToInt32(ProcessingDate().Year.ToString()) - 1;

            for (var n = LastYear; n < NextYear; n++)
            {
                ddlYear.Items.Add(n.ToString());
            }
        }
        
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string ActType = "INSERT";
            bool IsValidEntry = false;

            Int64 TargetAmount = 0, TargetAmountReal = 0;
            Int32 TargetNoa = 0, TargetNoaReal = 0;
            
            Int64 TotalAmount = Convert.ToInt64(lblAmount.Text.Replace(",",""));
            Int64 TotalNoa = Convert.ToInt64(lblNoa.Text.Replace(",", ""));

            foreach (GridViewRow row in gvList.Rows)
            {
                TextBox txtTargetAmount = (TextBox)row.FindControl("txtTargetAmount");
                TextBox txtTargetNoa = (TextBox)row.FindControl("txtNoa");

                if (txtTargetAmount.Text != "" && txtTargetNoa.Text != "")
                {
                    TargetAmount += Convert.ToInt64(txtTargetAmount.Text);
                    TargetNoa += Convert.ToInt32(txtTargetNoa.Text);
                }
            }

            if ((TargetAmount <= TotalAmount) && (TargetNoa <= TotalNoa)) IsValidEntry = true;

            if (IsValidEntry)
            {
                Shuba.Business.ClusterTarget _ClusterTarget = new Shuba.Business.ClusterTarget();
                Shuba.Model.ClusterTargetInfo bi = new Shuba.Model.ClusterTargetInfo();

                foreach (GridViewRow row in gvList.Rows)
                {
                    TextBox txtTargetAmount = (TextBox)row.FindControl("txtTargetAmount");
                    TextBox txtTargetNoa = (TextBox)row.FindControl("txtNoa");

                    TextBox txtTargetAmountReal = (TextBox)row.FindControl("txtTargetAmountReal");
                    TextBox txtTargetNoaReal = (TextBox)row.FindControl("txtNoaReal");

                    RangeValidator AmountValidator = (RangeValidator)row.FindControl("RangeValidatorAmount");
                    RangeValidator NoaValidator = (RangeValidator)row.FindControl("RangeValidatorNoa");

                    RangeValidator AmountValidator2 = (RangeValidator)row.FindControl("RangeValidatorAmountReal");
                    RangeValidator NoaValidator2 = (RangeValidator)row.FindControl("RangeValidatorNoaReal");

                    if (txtTargetAmount.Text != "") TargetAmount = Convert.ToInt64(txtTargetAmount.Text); else TargetAmount = 0;
                    if (txtTargetNoa.Text != "") TargetNoa = Convert.ToInt32(txtTargetNoa.Text); else TargetNoa = 0;
                    if (txtTargetAmountReal.Text != "") TargetAmountReal = Convert.ToInt64(txtTargetAmountReal.Text); else TargetAmountReal = 0;
                    if (txtTargetNoaReal.Text != "") TargetNoaReal = Convert.ToInt32(txtTargetNoaReal.Text); else TargetNoaReal = 0;

                    //string id = Convert.ToString(gvList.DataKeys[row.RowIndex].Value.ToString());

                    bi.ClusterID = Convert.ToString(gvList.DataKeys[row.RowIndex].Value.ToString());
                    bi.TargetYear = ddlYear.Text;
                    bi.TargetAmount = TargetAmount;
                    bi.Noa = TargetNoa;
                    bi.TargetAmountReal = TargetAmountReal;
                    bi.NoaReal = TargetNoaReal;
                    bi.EntryBy = HttpContext.Current.User.Identity.Name;
                    bi.EntryDate = ProcessingDate();
                    bi.UpdateBy = HttpContext.Current.User.Identity.Name;
                    bi.UpdateDate = ProcessingDate();
                    bi.ActType = ActType;

                    _ClusterTarget.Save(bi);

                    AmountValidator.Visible = false;
                    NoaValidator.Visible = false;

                    AddLog(ActType, ActType + " CLUSTER TARGET PLAN");
                }

                msg = this.GetGlobalResourceObject("Messages", "SaveAlert").ToString();
                AlertAndRedirect(msg, "cluster_plan_list.aspx");
            }
            else
            {
                Alert("Total Original NOA or Total Original Amount can not greater than Region Target Plan, please confirm your entry");
            }
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {                
                TextBox txtNoa = (TextBox)e.Row.FindControl("txtNoa");
                TextBox txtTargetAmount = (TextBox)e.Row.FindControl("txtTargetAmount");

                TextBox txtNoaReal = (TextBox)e.Row.FindControl("txtNoaReal");
                TextBox txtTargetAmountReal = (TextBox)e.Row.FindControl("txtTargetAmountReal");

                if (txtNoa.Text != "") TotalNoaCluster += Convert.ToInt64(txtNoa.Text);
                if (txtTargetAmount.Text != "") TotalAmountCluster += Convert.ToInt64(txtTargetAmount.Text);
                if (txtNoaReal.Text != "") TotalNoaClusterReal += Convert.ToInt64(txtNoaReal.Text);
                if (txtTargetAmountReal.Text != "") TotalAmountClusterReal += Convert.ToInt64(txtTargetAmountReal.Text);
            }
        }

        private void InitRegionList()
        {
            Shuba.Business.Regional _Region = new Shuba.Business.Regional();
            List<RegionalInfo> list;

            list = _Region.GetList("%", Session["UnitID"].ToString(), HttpContext.Current.User.Identity.Name, ConfigurationManager.AppSettings["app.code"]);
            ddlRegion.DataTextField = "RegionalName";
            ddlRegion.DataValueField = "RegionalID";
            ddlRegion.DataSource = list;

            ddlRegion.DataBind();

            if (ddlRegion.Items.Count == 0)
            {
                ListItem ListAll = new ListItem();
                ListAll.Value = "";
                ListAll.Text = "";
                ddlRegion.Items.Insert(0, ListAll);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("cluster_plan_list.aspx");
        }
    }
}
